package org.zs.rocketclient.order;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author madison
 * @description
 * @date 2021/7/4 09:31
 */
public class OrderedConsumer {

    public static void main(String[] args) throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("OrderedConsumer_group_name");
        consumer.setNamesrvAddr("localhost:9876");
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

        consumer.subscribe("OrderedTopicTest", "TagA || TagC || TagD");

        consumer.registerMessageListener(new MessageListenerOrderly() {

            AtomicLong consumeTimes = new AtomicLong(0);

            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs,
                                                       ConsumeOrderlyContext context) {
                context.setAutoCommit(false);
                System.out.printf(Thread.currentThread().getName() + " Receive New Messages: " + msgs + "%n");
                System.out.printf("\t\t\t\t Size: %d, Body: %s, TAGS: %s, KEYS: %s%n", msgs.size(),
                        new String(msgs.get(0).getBody()),
                        msgs.get(0).getTags(),
                        msgs.get(0).getKeys());
                this.consumeTimes.incrementAndGet();
                long consumeTime = this.consumeTimes.get();
                System.out.println("consumeTime: " + consumeTime);
                if ((consumeTime % 2) == 0) {
                    return ConsumeOrderlyStatus.SUCCESS;
                } else if ((consumeTime % 3) == 0) {
                    return ConsumeOrderlyStatus.ROLLBACK;
                } else if ((consumeTime % 4) == 0) {
                    return ConsumeOrderlyStatus.COMMIT;
                } else if ((consumeTime % 5) == 0) {
                    context.setSuspendCurrentQueueTimeMillis(3000);
                    return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });

        consumer.start();

        System.out.printf("Consumer Started.%n");
    }
}
